package com.Controller;

import com.Service.GroupActivityService;
import com.Service.ProductService;
import com.pojo.GroupActivity;
import com.pojo.GroupActivityVO;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/group")
public class AdminGroupController {

    @Resource
    private GroupActivityService groupActivityService;

    @Autowired
    private ProductService productService;

    // 列表页
    @GetMapping("/list")
    public String list(Model model) {
        List<GroupActivityVO> list = groupActivityService.findAllVO(); // 注意：调用返回 VO 的方法
        model.addAttribute("groupList", list);
        System.out.println(list);
        return "admin/group/list";
    }

    // 新增页跳转
    @GetMapping("/addPage")
    public String addPage(Model model) {
        model.addAttribute("productList", productService.findAll()); // 为下拉框准备商品列表
        return "admin/group/add";
    }

    // 编辑页跳转
    @GetMapping("/editPage")
    public String editPage(@RequestParam("id") Long id, Model model) {
        GroupActivityVO activity = groupActivityService.findVOById(id); // 使用VO对象
        model.addAttribute("group", activity); // 你的JSP页面用的变量名是 group
        model.addAttribute("productList", productService.findAll()); // 商品下拉框
        return "admin/group/add"; // 复用add.jsp页面
    }

    // 保存新增
    @PostMapping("/add")
    public String add(GroupActivity activity) {
        groupActivityService.add(activity);
        return "redirect:/admin/group/list";
    }

    // 保存编辑
    @PostMapping("/edit")
    public String edit(GroupActivity activity) {
        groupActivityService.update(activity);
        return "redirect:/admin/group/list";
    }

    // 删除
    @GetMapping("/delete")
    public String delete(@RequestParam("id") Long id, RedirectAttributes redirectAttributes) {
        try {
            groupActivityService.delete(id);
            redirectAttributes.addFlashAttribute("successMessage", "删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除失败：该拼团活动有关联数据，无法删除！");
        }
        return "redirect:/admin/group/list";
    }
}
